import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
    baseURL: '/' // url = base url + request url
})

// request interceptor
service.interceptors.request.use(
    (config) => {
        // do something before request is sent

        if (store.getters.token) {
            // please modify it according to the actual siuation
            config.headers['authorization'] = encodeURIComponent(getToken())
        }
        return config
    },
    (error) => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    (response) => {
        const res = response.data
        console.log('dsdsdds--->', res)
        if (res.code === 10001) {
            Message.closeAll()
            console.log(router);
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 2 * 1000,
                onClose: async () => {
                    await store.dispatch('user/resetToken')
                    router.push({ path: '/admin/login' })
                }
            })
            return res
        }
        if (res.code !== 200) {
            Message.closeAll()
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 3 * 1000
            })
        }
        return res
    },
    (error) => {
        console.log('err，' + error) // for debug
        // token过期
        if (error.response.retcode === 401) {
            Message.closeAll()
            Message({
                message: '登录过期，请重新登录',
                type: 'error'
            })
            return Promise.reject(error)
        }
        Message({
            message: error.message,
            type: 'error',
            duration: 3 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
